package com.shoujifeng.snowmusic.player;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.shoujifeng.snowmusic.player.R;
import com.shoujifeng.snowmusic.db.DatabaseUtil;
import com.shoujifeng.snowmusic.entity.Mp3Info;
import com.shoujifeng.snowmusic.player.http.GlobalValue;
import com.shoujifeng.snowmusic.player.http.ServerAccess;
import com.shoujifeng.snowmusic.player.utils.MediaUtil;
import com.shoujifeng.snowmusic.player.utils.MusicPlayer;
import com.shoujifeng.snowmusic.player.utils.TabHostAnim;

/**
 * 
 * @author Administrator 
 * 
 */
public class NativeMusicManageActivity extends Activity {
	private RelativeLayout downLoadLayout;
	private RelativeLayout nativeMusicLayout;
	private RelativeLayout myCollectSingleLayout;
	private RelativeLayout myLikeMusicLayout;
	private Button manageBtn;
	private Button setButton;
	final int SINGLE_DIALOG = 0x113;
	private ListView musicMenu;
	private MyAdapter mAdapter;
	private View mMoreView;
	private View mNativeMusicManage;
	private List<HashMap<String, Object>> arrayList;
	private boolean mSetManageLayView;
	public static String menu_name = "";
	public static String activityName = "";   
	public static String musicName ="";
	private List<Mp3Info> mp3Infos;
	private MediaUtil mediaUtil;
	private Thread accThread;
	private TextView countTxt;
	private ImageView user_headImgView;
	private TextView user_headTxt;
	private Button wifiBtn;
	private String mWifiString;
	private SharedPreferences spf;
	private String nickName;
	private String uid;
	private String code;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.native_music_manage_list);
		init();
	}
	 
	@Override
	protected void onResume() {
		
		if(user_headTxt != null) {
			if(ServerAccess.uid > 0) {
				user_headTxt.setText(ServerAccess.nickname);
				
				DatabaseUtil databaseUtil = new DatabaseUtil(NativeMusicManageActivity.this);
				TextView collect = (TextView) mNativeMusicManage.findViewById(R.id.arrowscountTxt);
				 collect.setText("共"+databaseUtil.getConllectSize()+"首歌曲");
			}
			else {
				user_headTxt.setText("点击登录/注册");
				user_headTxt.setOnClickListener(loginOnClickListener);
			}
		} 
		
		String value = spf.getString(ServerAccess.SET_WIFI, "no"); 
		if(value.endsWith("yes"))
		{
			wifiBtn.setBackgroundDrawable( getResources().getDrawable(R.drawable.bg_mymusic_setting_wifi_s));
		}
		else {
			wifiBtn.setBackgroundDrawable( getResources().getDrawable(R.drawable.bg_mymusic_setting_wifi_n));
		}
		
		setMenuList();
		mAdapter.notifyDataSetChanged();
		
		setMenuList();
		super.onResume();
	}



	public void init() {
		spf = PreferenceManager.getDefaultSharedPreferences(NativeMusicManageActivity.this);
		musicMenu = (ListView) findViewById(R.id.songMenuList);
		musicMenu.setDivider(null);
		mMoreView = LayoutInflater.from(NativeMusicManageActivity.this)
				.inflate(R.layout.song_menu_add, null);
		
		mNativeMusicManage = LayoutInflater
				.from(NativeMusicManageActivity.this).inflate(
						R.layout.native_music_manage, null);
		nativeMusicLayout = (RelativeLayout) mNativeMusicManage
				.findViewById(R.id.native_music_layout);
		
		mediaUtil  		= new MediaUtil();
	    mp3Infos 		= mediaUtil.getMp3Infos(NativeMusicManageActivity.this);
	    countTxt		= (TextView) mNativeMusicManage.findViewById(R.id.countTxt);
	   
	    
	    countTxt.setText("共"+mp3Infos.size()+"首歌曲");
		downLoadLayout 		= (RelativeLayout) mNativeMusicManage.findViewById(R.id.downLoadLayout);
		myLikeMusicLayout 	= (RelativeLayout) mNativeMusicManage.findViewById(R.id.myLikeMusic);
		myCollectSingleLayout = (RelativeLayout) mNativeMusicManage.findViewById(R.id.myCollectSingleLayout);
		
		musicMenu.addHeaderView(mNativeMusicManage);
		musicMenu.addFooterView(mMoreView);
		
		manageBtn 			= (Button) mNativeMusicManage.findViewById(R.id.manageBtn);
		setButton 			= (Button) findViewById(R.id.setBtn);
		user_headImgView 	= (ImageView) findViewById(R.id.user_headImgView);
		user_headTxt 		= (TextView) findViewById(R.id.user_headTxt);
		wifiBtn 			= (Button) findViewById(R.id.wifiBtn);
		
		String value = spf.getString(ServerAccess.SET_WIFI, ""); 
		mWifiString = value;
		
		if(value.equals("yes")){
			wifiBtn.setBackgroundDrawable( getResources().getDrawable(R.drawable.bg_mymusic_setting_wifi_s));
		}
		
		wifiBtn.setOnClickListener(onWifiClickListener);
		
		nickName = spf.getString(ServerAccess.NICKNAME,""); 
		uid = spf.getString(ServerAccess.UID, "0");
		
		ServerAccess.uid = Long.parseLong(uid);
		ServerAccess.code = spf.getString(ServerAccess.CODE, "");
		ServerAccess.number = spf.getString(ServerAccess.NUMBER, "");
		ServerAccess.nickname = nickName;
		
		if(ServerAccess.uid > 0) {
			writeConllect(ServerAccess.uid);
		}
		
		code = spf.getString(ServerAccess.CODE, "");
		if(!nickName.equals("")&&code.equals("1")){
			user_headTxt.setText(nickName);
		}
		else{
			user_headTxt.setText(R.string.native_music_manage_login);
		}
		setMenuList();
		setOnClickListener();
	}
	
	private View.OnClickListener onWifiClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			
			String value = spf.getString(ServerAccess.SET_WIFI, ""); 
			mWifiString = value;
			
			int status = 1;
			if(mWifiString.endsWith("yes"))
				status = 0;
			
			if(status==0){
				//写入数据到配置文件中        关闭状态
			      Editor edit = spf.edit();
			      edit.putString(ServerAccess.SET_WIFI, "no");
			      edit.commit();
			      
			      wifiBtn.setBackgroundDrawable( getResources().getDrawable(R.drawable.bg_mymusic_setting_wifi_n));
			      
			      Toast.makeText(NativeMusicManageActivity.this, "已关闭仅wifi联网", Toast.LENGTH_SHORT).show();
			}
			if(status ==1){     //打开状态
			      Editor edit = spf.edit();
			      edit.putString(ServerAccess.SET_WIFI, "yes");
			      edit.commit();
			      wifiBtn.setBackgroundDrawable( getResources().getDrawable(R.drawable.bg_mymusic_setting_wifi_s));
			      
			      Toast.makeText(NativeMusicManageActivity.this, "开启仅wifi联网, 全面保护流量!", Toast.LENGTH_SHORT).show();
			}
			
		}
	};

	public void setOnClickListener() {
		mMoreView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ServerAccess.musicMap.clear();
				
				Intent intent = new Intent(NativeMusicManageActivity.this,
						NewSongMenuActivity.class);
				startActivity(intent);
				TabHostAnim.set(R.anim.right_in, R.anim.no_move);
				
			}
		});
		nativeMusicLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(NativeMusicManageActivity.this,
						NativeMusicTab.class);
				startActivity(intent);
				
				//((MyTabHost)getParent()).createInActivity(0, null);
				
				TabHostAnim.set(R.anim.right_in, R.anim.no_move);
			}
		});
		
		downLoadLayout.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(NativeMusicManageActivity.this,
						DownLoadTab.class);
				startActivity(intent);
				TabHostAnim.set(R.anim.right_in, R.anim.no_move);
			}
		});
		myCollectSingleLayout.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(ServerAccess.uid > 0)
				{
					Intent intent = new Intent(NativeMusicManageActivity.this,
							MyCollectSingleActivity.class);
					startActivity(intent);
				}
				else {
					Intent intent = new Intent(NativeMusicManageActivity.this, LoginActivity.class);
					startActivity(intent);
				}
				TabHostAnim.set(R.anim.right_in, R.anim.no_move);
			}
		});
		
		manageBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mSetManageLayView == true) {
					mSetManageLayView = false;
					
					manageBtn.setText("管理");
					mAdapter.notifyDataSetChanged();
				} else {
					mSetManageLayView = true;
					manageBtn.setText("完成");
					mAdapter.notifyDataSetChanged();
				}

			}
		});

		musicMenu.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				TextView songMenuName = (TextView) view
						.findViewById(R.id.songMenuName);
				Intent intent = new Intent(NativeMusicManageActivity.this,
						MusicMenuContentActivity.class);
				intent.putExtra("name", songMenuName.getText()
						.toString());
				musicName = songMenuName.getText().toString();
				startActivity(intent);
				TabHostAnim.set(R.anim.right_in, R.anim.no_move);
			}
		});
		
		myLikeMusicLayout.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(NativeMusicManageActivity.this,
						MusicMenuContentActivity.class);
				intent.putExtra("name","我喜欢的歌曲");
				musicName ="我喜欢的歌曲";
				startActivity(intent);
				TabHostAnim.set(R.anim.right_in, R.anim.no_move);
			}
		});
		
		setButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getParent().getApplicationContext(),
						setActivity.class);
				startActivity(intent);
				
				TabHostAnim.set(R.anim.right_in, R.anim.no_move);
			}
		});
		
		user_headTxt.setOnClickListener(loginOnClickListener);

	}
	
	private View.OnClickListener loginOnClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			if(nickName.equals("")||!code.equals("1")){
				Intent intent = new Intent(NativeMusicManageActivity.this,LoginActivity.class);
				startActivity(intent);
				TabHostAnim.set(R.anim.right_in, R.anim.no_move);
			}
		}
	};

	public void setMenuList() {
		if(arrayList != null)
			arrayList.clear();
		
		DatabaseUtil databaseUtil = new DatabaseUtil(this);
		arrayList = new ArrayList<HashMap<String, Object>>();
		arrayList = databaseUtil.queryMusicMenu();
		mAdapter = new MyAdapter(this, arrayList, R.layout.song_menu_list,
				new String[] { "name" }, new int[] { R.id.songMenuName });
		musicMenu.setAdapter(mAdapter);
	}

	private class MyAdapter extends SimpleAdapter {
		int count = 0;
		private List<HashMap<String, Object>> mItemList;

		public MyAdapter(Context context,
				List<HashMap<String, Object>> arrayList, int songMenuList,
				String[] strings, int[] is) {
			super(context, arrayList, songMenuList, strings, is);
			mItemList = arrayList;
			if (arrayList == null) {
				count = 0;
			} else {
				count = arrayList.size();
			}
			// TODO Auto-generated constructor stub
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mItemList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return mItemList.size();
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			
			HashMap<String, Object> map = mItemList.get(position);
			final String name 			= (String) map.get("name");
			View view 					= super.getView(position, convertView, parent);
			TextView nameText 			= (TextView) view.findViewById(R.id.songMenuName);
			
			nameText.setText(name);
			LinearLayout manageLay = (LinearLayout) view
					.findViewById(R.id.manageLay);
			ImageView imageView = (ImageView) view.findViewById(R.id.toImage);
			if (mSetManageLayView == false) {
				manageLay.setVisibility(View.GONE);
				imageView.setVisibility(View.VISIBLE);
			}
			if (mSetManageLayView == true) {
				manageLay.setVisibility(View.VISIBLE);
				imageView.setVisibility(View.GONE);
			}

			Button editBtn = (Button) view.findViewById(R.id.editBtn);
			Button removeBtn = (Button) view.findViewById(R.id.removeBtn);

			editBtn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(NativeMusicManageActivity.this,
							NewSongMenuActivity.class);
					menu_name = name;
					intent.putExtra("name", menu_name);
					startActivityForResult(intent, 1);
					TabHostAnim.set(R.anim.right_in, R.anim.no_move);
				}
			});
			removeBtn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					menu_name = name;
					Intent intent = new Intent(NativeMusicManageActivity.this,
							RemoveSongMenuActivity.class);
					menu_name = name;
					intent.putExtra("name", menu_name);
					startActivityForResult(intent, 2);
					TabHostAnim.set(R.anim.right_in, R.anim.no_move);
					
				}
			});

			return view;
		}
	}



	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode == RESULT_OK){
			String result = data.getExtras().getString("name");
			String newName = data.getExtras().getString("newName");
			for(int i =0; i<arrayList.size();i++){
				if(arrayList.get(i).get("name").equals(result)){
					HashMap<String,Object> map = new HashMap<String, Object>();
					map.put("name", newName);
					arrayList.set(i, map);
				}
			}
		}
		if(resultCode == 2){
			String result = data.getExtras().getString("breakName");
			for(int i =0; i<arrayList.size();i++){
				if(arrayList.get(i).get("name").equals(result)){
					arrayList.remove(i);
				}
			}
		}
		mAdapter.notifyDataSetChanged();
	}
	
	protected Runnable runnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				
				}
			 catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}

		}
	};
	
	//获取收藏数据
		//By Kress
		private void writeConllect(final long uid)
		{
			new AsyncTask<Integer, Integer, Integer>()
			{

				@Override
				protected Integer doInBackground(Integer... params) {
					try {
						ServerAccess serverAccess = new ServerAccess(NativeMusicManageActivity.this);
						ArrayList<HashMap<String, Object>> arrayList = serverAccess.getConllect(uid, -1, new String[]{"index"});
						if(arrayList != null && arrayList.size() > 0) 
						{
							DatabaseUtil db = new DatabaseUtil(NativeMusicManageActivity.this);
							db.clearConllect();
							
							int count = arrayList.size();
							for(int i = 0; i < count; i++) {
								HashMap<String, Object> map = arrayList.get(i);
								
								db.insertConllect(Integer.parseInt(map.get("index").toString()), uid);
							}
							
							publishProgress(count);
						}
						
						
					} catch (Exception e) {
						// TODO: handle exception
					}
					return null;
				}

				@Override
				protected void onProgressUpdate(Integer... values) {

					 TextView collect = (TextView) mNativeMusicManage.findViewById(R.id.arrowscountTxt);
					 collect.setText("共"+values[0]+"首歌曲");
					super.onProgressUpdate(values);
				}
				
				
			}.execute(0);
		}
}
